import axios, { AxiosResponse, AxiosRequestConfig } from "axios";
import { useUserStore } from "@/store/user";
import { message } from "ant-design-vue";
import { aesEncrypt } from "@/components/verifition/utils/ase";
const { VITE_BASE_URL, VITE_REQUEST_URL_PREFIX } = import.meta.env;

// 接口加密密钥--请自行修改
const key = "TigShopApiSecret";
const requestSecret = () => {
    const currentTimeStamp = Math.floor(Date.now() / 1000);
    const secret = aesEncrypt(currentTimeStamp, key);
    return secret;
};

const requestUrl = {
    prefix: VITE_BASE_URL + VITE_REQUEST_URL_PREFIX, // 所有的请求地址前缀部分
    headers: {
        Authorization: "Bearer " + localStorage.getItem("accessToken"),
        "X-Shop-Id": localStorage.getItem("shopId"),
        "X-Client-Type": "admin"
    }
};

// 创建一个 axios 实例
const createAxiosInstance = (baseURL: string) => {
    return axios.create({
        baseURL, // 请求前缀
        timeout: 60000, // 请求超时时间毫秒
        headers: { "Content-Type": "application/json" }
    });
};

// 添加请求拦截器
const setupInterceptors = (instance: any) => {
    instance.interceptors.request.use(
        (config: AxiosRequestConfig) => {
            // 在发送请求之前做些什么
            config.headers!["Authorization"] = "Bearer " + localStorage.getItem("accessToken");
            config.headers!["X-Shop-Id"] = localStorage.getItem("shopId");
            config.headers!["X-Client-Type"] = "admin";
            // config.headers["Secret"] = requestSecret();
            return config;
        },
        (error: any) => Promise.reject(error) as any
    );

    // 添加响应拦截器
    instance.interceptors.response.use(
        (response: AxiosResponse) => {
            return response.data;
        },
        (error: any) => {
            if (error.response) {
                const store = useUserStore() as any;
                const data = error.response.data;
                const status = error.response.status;
                if (status === 403 || status === 401) {
                    // 禁止访问、无效Token
                    message.error("登录已过期，请重新登录");
                    store.logout();
                } else if (data.msg) {
                    message.error(data.msg);
                }
            }
            return Promise.reject(error) as any;
        }
    );
};

type ApiResponse<T> = T & {
    errcode: number;
    message: string;
};

// 扩展 AxiosRequestConfig 接口以包含 prefix 参数
interface CustomAxiosRequestConfig extends AxiosRequestConfig {
    prefix?: string;
}
import router from "@/router";
export function request<T>(config: CustomAxiosRequestConfig): Promise<ApiResponse<T>> {
    const prefix = config.prefix || VITE_REQUEST_URL_PREFIX;
    const baseURL = `${VITE_BASE_URL}${prefix}`;
    const axiosInstance = createAxiosInstance(baseURL);
    setupInterceptors(axiosInstance);
    return axiosInstance(config).then((response: AxiosResponse<ApiResponse<T>>) => {
        if (config.responseType) {
            if (response.data && response.data.errcode > 0) {
                return Promise.reject(response.data as any) as any;
            }
            return response;
        } else {
            if (response.data && response.data.errcode === 401) {
                localStorage.removeItem("accessToken");
                localStorage.removeItem("shopId");
                localStorage.removeItem("user");
                localStorage.removeItem("lastOpenTime");
                setTimeout(() => {
                    window.location.reload()
                    router.push("/login/index")
                }, 200);
            }else if (response.data.errcode > 0 && response.data.errcode != 401) {
                return Promise.reject(response.data as any) as any;
            }else {
                return response.data;
            }
        }
    });
}

export default request;

export { requestUrl };
